<template>
  <div class="role-management">
    <el-button color="#19af7d" @click="addRole" style="margin-bottom: 20px"
      >新增角色</el-button
    >

    <el-table :data="roleList" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="80" align="center" />
      <el-table-column prop="name" label="角色名称" align="center" />
      <el-table-column prop="description" label="描述" align="center" />
      <el-table-column label="操作" width="180" align="center">
        <template #default="scope">
          <el-button size="small" @click="editRole(scope.row)">编辑</el-button>
          <el-button
            size="small"
            type="danger"
            @click="deleteRole(scope.row.id)"
            >删除</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <Form
      v-model="dialogVisible"
      :isEdit="isEdit"
      :roleFormData="roleForm"
      @save="handleSave"
    />
  </div>
</template>

<script setup>
import { ref, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import Form from "./form.vue";

// 所有角色数据
const allRoles = ref([
  { id: 1, name: "管理员", description: "拥有所有权限" },
  { id: 2, name: "普通用户", description: "基本操作权限" },
]);

const dialogVisible = ref(false);
const isEdit = ref(false);
// 角色表单数据
const roleForm = ref({ id: null, name: "", description: "" });

// 角色列表
const roleList = computed(() => [...allRoles.value]);

const addRole = () => {
  isEdit.value = false;
  roleForm.value = { id: null, name: "", description: "" };
  dialogVisible.value = true;
};

const editRole = (row) => {
  isEdit.value = true;
  roleForm.value = { ...row };
  dialogVisible.value = true;
};

const generateId = () => {
  return Math.max(...allRoles.value.map((item) => item.id), 0) + 1;
};

const handleSave = (data) => {
  dialogVisible.value = false;
  if (isEdit.value) {
    const index = allRoles.value.findIndex((item) => item.id === data.id);
    if (index !== -1) {
      allRoles.value = [
        ...allRoles.value.slice(0, index),
        data,
        ...allRoles.value.slice(index + 1),
      ];
    }
  } else {
    const newRole = { ...data, id: generateId() };
    allRoles.value = [...allRoles.value, newRole];
  }
  ElMessage.success(isEdit.value ? "编辑角色成功" : "新增角色成功");
};

const deleteRole = (id) => {
  ElMessageBox.confirm("确定要删除该角色吗？", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      allRoles.value = allRoles.value.filter((item) => item.id !== id);
      ElMessage.success("删除角色成功");
    })
    .catch(() => {});
};
</script>

<style scoped lang="scss"></style>
